package dev.ece.util.arrays;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class ReverseIterator<T> implements Iterator<T> {
	
	private int startIndex;
	
	private List<T> list;
	
	private Object[] array;
	
	public ReverseIterator(List<T> list) {
		this.list = list;
		this.array = list.toArray();
		this.startIndex = this.array.length - 1;
	}

	@Override
	public boolean hasNext() {
		return startIndex > -1;
	}

	@Override
	@SuppressWarnings("unchecked")
	public T next() {
		synchronized (list) {
			if (!hasNext())
                throw new NoSuchElementException();
			return (T) array[startIndex --];
		}
	}

	@Override
	public void remove() {
		synchronized (list) {
			int index = startIndex + 1;
			list.remove(index);
		}
	}

}
